//
//  AnimeViewController.m
//  GentlemanAnime
//
//  Created by dlios on 15-6-29.
//  Copyright (c) 2015年 lanou3g.com 蓝欧科技. All rights reserved.
//

#import "AnimeViewController.h"
#import "AnimeCollectionViewCell.h"
#import "UIImageView+WebCache.h"
#import "HTTPTool.h"
#import "AnimeControllerViewModel.h"
#import "EpisodeModel.h"
#import "AnimeDetallsViewController.h"
#import "EpisodeModel.h"
#import "SearchViewController.h"
#import "AppDelegate.h"
#import "AFNetworking.h"
#import "AFNetworkReachabilityManager.h"


#import "DownloadSingletonTool.h"
#import "CDSideBarController.h"
#import "MBProgressHUD.h"


//后添加的为了去掉轮播图的bug
#import "QCRound.h"


#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height

typedef NS_ENUM(NSInteger, AnimeStyle) {
    indexStyle,
    newStyle,
    lanzaiStyle,
    wanjieStyle,
    yuanchuangStyle
};

//添加一个代理
@interface AnimeViewController () <UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate,CDSideBarControllerDelegate,QCRoundDelegate>
@property(nonatomic, retain)NSMutableArray *dataIndexArr;
@property(nonatomic, retain)NSMutableArray *dataLuboArr;
@property(nonatomic, retain)NSMutableArray *dataNewArr;
@property(nonatomic, retain)NSMutableArray *dataLianzaiArr;
@property(nonatomic, retain)NSMutableArray *dataWanjieArr;
@property(nonatomic, retain)NSMutableArray *dataYuanchuangArr;
@property(nonatomic, retain)UICollectionView *collectionView;
@property(nonatomic, retain)UIScrollView *scrollView;
@property(nonatomic, assign)NSInteger animeStyle;
@property(nonatomic, retain)HeadlinesModel *headModel;
@property(nonatomic, retain)MBProgressHUD *HUD;
@property(nonatomic, retain)UIImageView *startImageView;
@property(nonatomic, retain)UIView *startView;

@property(nonatomic, retain)CDSideBarController *sideBar;
@property(nonatomic, retain)NSArray *sideBartitlesArr;

@property (nonatomic, strong) QCRound *round;

@end

@implementation AnimeViewController

- (void)dealloc
{
    [_sideBartitlesArr release];
    [_sideBar release];
    [_dataLuboArr release];
    [_dataIndexArr release];
    [_dataNewArr release];
    [_dataLianzaiArr release];
    [_dataWanjieArr release];
    [_dataYuanchuangArr release];
    [_collectionView release];
    [_scrollView release];
    [_headModel release];
    [_startImageView release];
    [_startView release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.animeStyle = indexStyle;
        self.dataLuboArr = [NSMutableArray array];
        self.sideBartitlesArr = @[@"推荐",@"最新",@"连载",@"完结",@"原创",@"收回"];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    UILabel *titlelebel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
    titlelebel.text = @"漫画";
    titlelebel.font = [UIFont boldSystemFontOfSize:18];
    titlelebel.textAlignment = NSTextAlignmentCenter;
    titlelebel.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = titlelebel;
    [titlelebel release];
    
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = [UIColor yellowColor];
    
    [self createData];
    
    // 建立左右两个button
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeSystem];
    rightButton.frame = CGRectMake(0, 0, 30, 30);
    [rightButton setImage:[UIImage imageNamed:@"搜索"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(rightClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
    leftButton.frame = CGRectMake(0, 0, 30, 30);
    [leftButton setImage:[UIImage imageNamed:@"用户1"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(leftClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    
    
    // 创建一个瀑布流效果
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake((WIDTH - 60) / 3, ((WIDTH - 60) / 3) * 34 / 21);
    flowLayout.minimumLineSpacing = 10;
    flowLayout.minimumInteritemSpacing = 15;
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 15, 10, 15);
    

    
    // 创建CollectionView
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.contentInset = UIEdgeInsetsMake(WIDTH * 200 / 375, 0, 0, 0);
    [self.view addSubview:self.collectionView];
    [_collectionView release];
    
    // 注册
    [self.collectionView registerClass:[AnimeCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    
    // 小菊花下面的挡板
    self.startView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 113)];
    [self.view addSubview:self.startView];
    [_startView release];
    
    
    // 小菊花
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.color = [UIColor colorWithRed:0.334 green:0.619 blue:1.000 alpha:1.000];
    self.HUD.mode = MBProgressHUDModeIndeterminate;
}

- (void)createLunBoTun {
    self.round = [[QCRound alloc] initWithFrame:CGRectMake(0, -WIDTH * 200 / 375, WIDTH, WIDTH * 200 / 375)];
    NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"漫图占位图",@"漫图占位图",@"漫图占位图",@"漫图占位图",@"漫图占位图", nil];
    self.round.imageArr = arr;
    self.round.delegate = self;
    self.round.lubotuArr = self.dataLuboArr;
    [self.collectionView addSubview:self.round];
}


- (void)clickedIndexPath:(NSIndexPath *)indexPath {
    self.headModel = self.dataLuboArr[indexPath.row];
    AnimeDetallsViewController *animeDetallsVC = [[AnimeDetallsViewController alloc] init];
    animeDetallsVC.Id = self.headModel.headlinesId;
    animeDetallsVC.tuTitle = self.headModel.title;
    [self.navigationController pushViewController:animeDetallsVC animated:YES];
    [animeDetallsVC release];
}

#pragma mark 绘制侧边控制栏
- (void)createSideBar {
    self.sideBar = [[CDSideBarController alloc] initWithTitles:self.sideBartitlesArr];
    self.sideBar.delegate = self;
    [self.sideBar insertMenuButtonOnView:self.view atPosition:CGPointMake(self.view.frame.size.width - 60, HEIGHT - 170)];
    
    
}

#pragma mark 侧栏点击方法
- (void)menuButtonClicked:(NSInteger)index {
    switch (index) {
        case 0:
            self.animeStyle = indexStyle;
            break;
        case 1:
            self.animeStyle = newStyle;
            break;
        case 2:
            self.animeStyle = lanzaiStyle;
            break;
        case 3:
            self.animeStyle = wanjieStyle;
            break;
        case 4:
            self.animeStyle = yuanchuangStyle;
            break;
    }
    [self.collectionView reloadData];
}

// 解析数据
- (void)createData
{
    [HTTPTool get:@"http://api.dmzj.com/dynamic/index.json" body:nil httpResultStyle:JSON success:^(id result) {
        NSDictionary *dic = result;
        AnimeControllerViewModel *animeModel = [[AnimeControllerViewModel alloc] init];
        [animeModel setValuesForKeysWithDictionary:dic];
        // 数据归类
        [self structureData:(AnimeControllerViewModel *)animeModel];
        // 给轮播图赋值
//          [self setlunbotu];
        
        // 创建轮播图
        [self createLunBoTun];
         // 给轮播图的数组赋值
        self.round.imageArr = self.dataLuboArr;
        
         // 制订轮播图的样式
        [self.round configureCellBlock:^(QCRoundCell *cell, id model) {
            HeadlinesModel *focus = model;
            cell.imageUrl = focus.coverURL;
        }];
        [self.collectionView reloadData];
        self.startView.hidden = YES;
        [self.startView removeFromSuperview];
        [self.HUD hide:YES];
    
        // 侧边控制栏
        [self createSideBar];

    } failure:^(NSError *error) {
        
    }];
}

#pragma mark 数据规类
- (void)structureData:(AnimeControllerViewModel *)animeModel
{
    // 轮播图数组数据
    [self.dataLuboArr addObject:animeModel.animeindexModel.headlinesModel];
    [self.dataLuboArr addObject:animeModel.animeNewModel.headlinesModel];
    [self.dataLuboArr addObject:animeModel.animelianzaiModel.headlinesModel];
    [self.dataLuboArr addObject:animeModel.animewanjieModel.headlinesModel];
    [self.dataLuboArr addObject:animeModel.animeyuanchuangModel.headlinesModel];
    // 推荐数组数据
    self.dataIndexArr = animeModel.animeindexModel.episodeArr;
    // 最新数组数据
    self.dataNewArr = animeModel.animeNewModel.episodeArr;
    // 连载数组数据
    self.dataLianzaiArr = animeModel.animelianzaiModel.episodeArr;
    // 完结数组数据
    self.dataWanjieArr = animeModel.animewanjieModel.episodeArr;
    // 原创数组数据
    self.dataYuanchuangArr = animeModel.animeyuanchuangModel.episodeArr;
}

#pragma mark 给轮播图赋值
- (void)setlunbotu
{
    HeadlinesModel *lastModel = [self.dataLuboArr lastObject];
    [self.dataLuboArr insertObject:lastModel atIndex:0];
    HeadlinesModel *firstModel = [self.dataLuboArr objectAtIndex:1];
    [self.dataLuboArr addObject:firstModel];
//    NSLog(@"%d",self.dataLuboArr.count);
    self.scrollView.contentSize = CGSizeMake(WIDTH * self.dataLuboArr.count, 0);
    
    for (NSInteger i = 0; i < self.dataLuboArr.count; i++) {
        HeadlinesModel *tempModel = self.dataLuboArr[i];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * WIDTH, 0, WIDTH, WIDTH * 200 / 375)];
        imageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        [imageView addGestureRecognizer:tap];
        tap.numberOfTouchesRequired = 1;
        tap.numberOfTapsRequired = 1;
        [imageView sd_setImageWithURL:[NSURL URLWithString:tempModel.coverURL]];
        [self.scrollView addSubview:imageView];
        [imageView release];
        
        UIImageView *backImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"小图蒙板"]];
        backImageView.frame = CGRectMake(0, imageView.frame.size.height - 30, WIDTH, 30);
        [imageView addSubview:backImageView];
        [backImageView release];
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, WIDTH - 20, 30)];
        titleLabel.textColor = [UIColor whiteColor];
        titleLabel.font = [UIFont systemFontOfSize:14];
        NSString *str = [NSString stringWithFormat:@"<<%@>>%@", tempModel.title, tempModel.subtitle];
        titleLabel.text = str;
        [backImageView addSubview:titleLabel];
        [titleLabel release];
    }
}

#pragma mark 时间计时器
- (void)changeImage
{
    self.scrollView = (UIScrollView *)[self.collectionView viewWithTag:1000];
    [self.scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x + WIDTH, 0) animated:YES];
    if (self.scrollView.contentOffset.x == (self.dataLuboArr.count - 1) * WIDTH) {
        self.scrollView.contentOffset = CGPointMake(WIDTH, 0);
    }
}

#pragma mark 手动拨动轮播图
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (self.scrollView.contentOffset.x == (self.dataLuboArr.count - 1) * WIDTH) {
        self.scrollView.contentOffset = CGPointMake(WIDTH, 0);
    }else if (self.scrollView.contentOffset.x == 0){
        self.scrollView.contentOffset = CGPointMake((self.dataLuboArr.count - 2) * WIDTH, 0);
    }
}


#pragma mark collectionView的两个协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSInteger count = 0;
    switch (self.animeStyle) {
        case indexStyle:
            count = self.dataIndexArr.count;
            break;
        case newStyle:
            count =  self.dataNewArr.count;
            break;
        case lanzaiStyle:
            count =  self.dataLianzaiArr.count;
            break;
        case wanjieStyle:
            count =  self.dataWanjieArr.count;
            break;
        case yuanchuangStyle:
            count =  self.dataYuanchuangArr.count;
            break;
    }
    return count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    AnimeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    EpisodeModel *episodeModel = nil;
    switch (self.animeStyle) {
        case indexStyle:
            episodeModel = self.dataIndexArr[indexPath.row];
            break;
        case newStyle:
            episodeModel = self.dataNewArr[indexPath.row];
            break;
        case lanzaiStyle:
            episodeModel = self.dataLianzaiArr[indexPath.row];
            break;
        case wanjieStyle:
            episodeModel = self.dataWanjieArr[indexPath.row];
            break;
        case yuanchuangStyle:
            episodeModel = self.dataYuanchuangArr[indexPath.row];
            break;
        
    }
    [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:episodeModel.coverURL] placeholderImage:[UIImage imageNamed:@"漫画占位图"]];
    cell.nameLabel.text = episodeModel.last_update_chapter_name;
    cell.textLabel.text = episodeModel.title;
    return cell;
}

//#pragma mark 轮播图的点击方法
//- (void)tapAction:(UITapGestureRecognizer *)tap
//{
//    NSInteger offX = self.scrollView.contentOffset.x / WIDTH;
//    NSInteger index = 0;
//    if (offX == 0 || offX == self.dataLuboArr.count - 2) {
//        index = 0;
//    } else if (offX == 1 || offX == self.dataLuboArr.count - 1) {
//        index = 1;
//    } else {
//        index = offX;
//    }
//    self.headModel = self.dataLuboArr[index];
//    AnimeDetallsViewController *animeDetallsVC = [[AnimeDetallsViewController alloc] init];
//    animeDetallsVC.Id = self.headModel.headlinesId;
//    animeDetallsVC.tuTitle = self.headModel.title;
//    [self.navigationController pushViewController:animeDetallsVC animated:YES];
//    [animeDetallsVC release];
//}

#pragma maek collectionView的点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    AnimeDetallsViewController *animeDetallsVC = [[AnimeDetallsViewController alloc] init];
    [self.navigationController pushViewController:animeDetallsVC animated:YES];
    
    EpisodeModel *episodeModel = nil;
    switch (self.animeStyle) {
        case indexStyle:
            episodeModel = self.dataIndexArr[indexPath.row];
            break;
        case newStyle:
            episodeModel = self.dataNewArr[indexPath.row];
            break;
        case lanzaiStyle:
            episodeModel = self.dataLianzaiArr[indexPath.row];
            break;
        case wanjieStyle:
            episodeModel = self.dataWanjieArr[indexPath.row];
            break;
        case yuanchuangStyle:
            episodeModel = self.dataYuanchuangArr[indexPath.row];
            break;
    }
    animeDetallsVC.Id = episodeModel.epId;
    animeDetallsVC.tuTitle = episodeModel.title;
    [animeDetallsVC release];
}



#pragma mark 两个button的点击方法
- (void)leftClick:(UIButton *)button
{
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [tempAppDelegate.LeftSlideVC openLeftView];
}

- (void)rightClick:(UIButton *)button
{
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
    [searchVC release];
}

// top按钮
- (void)top {
    [self.collectionView setContentOffset:CGPointMake(0, -WIDTH * 200 / 375) animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
